package com.yc.springmvc;

import com.yc.springmvc.web.MyDispatcherServlet;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.filter.CharacterEncodingFilter;
import org.springframework.web.servlet.DispatcherServlet;

import javax.servlet.*;

public class MyWebApplicationInitializer implements WebApplicationInitializer {
    @Override
    public void onStartup(javax.servlet.ServletContext servletContext) throws ServletException {
        // 加载 Spring 配置
        AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
        context.register(MvcConfig.class);
        // 注册转发器Servlet
//        DispatcherServlet servlet = new DispatcherServlet(context);
        Servlet servlet = new MyDispatcherServlet();
        ServletRegistration.Dynamic registration = servletContext.addServlet("app", servlet);
        registration.setLoadOnStartup(1);
        registration.addMapping("/");

        // location : 上传文件临时保存的文件夹路径  "" or null 都表示使用默认的临时路径
        // maxFileSize : 最大的文件大小
        // maxRequestSize : 请求体总体大小 => 多文件上传
        // fileSizeThreshold : 临时保存文件大小阈值

        MultipartConfigElement multipartConfigElement = new MultipartConfigElement(
                null,1024*1024,-1L,0);
        registration.setMultipartConfig(multipartConfigElement);

        CharacterEncodingFilter filter = new CharacterEncodingFilter();
        filter.setEncoding("utf-8");
        filter.setForceEncoding(true);
        FilterRegistration.Dynamic charsetFilter = servletContext.addFilter("charsetFilter", filter);
        charsetFilter.addMappingForUrlPatterns(null,false,"/*");
    }
}
